package com.ishare.common.handler;

import com.ishare.common.constant.GlobalReturnCode;
import com.ishare.common.dto.VoData;
import com.ishare.common.dto.exception.GlobalException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 李嘉宾
 */
@ControllerAdvice(basePackages = "com.ishare")
@Component
public class GlobalExceptionHandler {

    /**
     * 拦截GlobalException
     *
     * @param globalException 业务全局异常
     * @return VoData
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public VoData exception(GlobalException globalException) {
        globalException.printStackTrace();
        return VoData.error(globalException.getCode(), globalException.getMsg(), globalException.getData());
    }

    /**
     * 拦截MethodArgumentNotValidException
     *
     * @param methodArgumentNotValidException 业务全局异常
     * @return VoData
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public VoData exception(MethodArgumentNotValidException methodArgumentNotValidException) {
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        FieldError fieldError = bindingResult.getFieldErrors().get(0);
        String defaultMessage = fieldError.getDefaultMessage();
        return VoData.error(GlobalReturnCode.PARAM_ERROR.getCode(), defaultMessage);
    }

    /**
     * 拦截IllegalArgumentException
     *
     * @param illegalArgumentException 参数异常
     * @return VoData
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public VoData exception(IllegalArgumentException illegalArgumentException) {
        illegalArgumentException.printStackTrace();
        return VoData.error(GlobalReturnCode.PARAM_ERROR.getCode(), GlobalReturnCode.PARAM_ERROR.getMsg());
    }


    /**
     * 拦截Exception
     *
     * @param exception 系统异常
     * @return VoData
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public VoData exception(Exception exception) {
        exception.printStackTrace();
        return VoData.error(GlobalReturnCode.SYSTEM_ERROR.getCode(), GlobalReturnCode.SYSTEM_ERROR.getMsg());
    }

}
